/**
 * 快递新增网点
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, message, Input } from 'antd';
import { layout3 } from '@/utils/config';
import { addNetwork } from '../../service';

export default ({ item, handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [open, setOpen] = useState(false);

  const [isOk, setIsOk] = useState(false);

  const onOk = () => {
    form.validateFields().then(val => {
      handleSubmit(val);
    })
  }

  useEffect(() => {
    setOpen(true)
  }, [])


  const handleSubmit = async val => {
    const { name } = val;
    START_LOADING();
    const res = await addNetwork({
      expressId: item.expressId,
      expressName: item.expressName,
      name
    })
    END_LOADING();
    if (res.success) {
      message.success('添加成功！')
      setOpen(false);
      setIsOk(true);
    }
  }

  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    if (isOk) {
      handleOk();
    }
    handleCancel();
  }

  return (
    <CommonModal
      title='新增网点'
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      afterClose={afterClose}
    >
      <Form
        {...layout3}
        name='add-inside-network'
        form={form}
        layout='horizontal'
      >
        <Form.Item label="网点名称" name="name" rules={[{ required: true, message: '网点名称不能为空' }, { pattern: /^\S{0,20}$/, message: '不能超过20个字符' }]}>
          <Input placeholder='请输入网点名称' />
        </Form.Item>
      </Form>
    </CommonModal>
  )
}